/*
 * cs 2020-9-26
 * 使用 native.js 调用原生实现 原生日历的 增删改查
 */
var calanderURL = "content://com.android.calendar/calendars";
var calanderEventURL = "content://com.android.calendar/events";
var calanderRemiderURL = "content://com.android.calendar/reminders";
var calId;
var ContentValues = plus.android.importClass("android.content.ContentValues");
var Uri = plus.android.importClass("android.net.Uri");
var main = plus.android.runtimeMainActivity();
var ContentUris = plus.android.importClass('android.content.ContentUris');

/*
 * cs 2020-9-26
 * 获取日历权限
 */
function getCalendarJurisdiction(sucFun, errFun) {
	plus.android.requestPermissions(['android.permission.READ_CALENDAR', 'android.permission.WRITE_CALENDAR'], function(
		e) {
		if (e.deniedAlways.length > 0) { //权限被永久拒绝
			// 弹出提示框解释为何需要定位权限，引导用户打开设置页面开启
			console.log('Always Denied!!! ' + e.deniedAlways.toString());
			if (errFun && typeof errFun == "function") {
				errFun({
					msg: "权限被永久拒绝了"
				})
			}
		}
		if (e.deniedPresent.length > 0) { //权限被临时拒绝
			if (errFun && typeof errFun == "function") {
				errFun({
					msg: "权限被临时拒绝了"
				})
			}
			// 弹出提示框解释为何需要定位权限，可再次调用plus.android.requestPermissions申请权限
			console.log('Present Denied!!! ' + e.deniedPresent.toString());
		}
		if (e.granted.length > 0) { //权限被允许
			//调用依赖获取定位权限的代码
			if (sucFun && typeof sucFun == 'function') {
				sucFun();
			}
		}
	})
}

/*
 * cs 2020-9-26
 * 查询日历
 */
function queryEvent(Obj) {
	// 首先获取权限
	return new Promise((resolve, reject) => {
		getCalendarJurisdiction(function() {
			var userCursor = plus.android.invoke(main.getContentResolver(), "query", Uri.parse(
					calanderEventURL),
				null, null,
				null, null);

			var count = plus.android.invoke(userCursor, "getCount");
			var tampArr = []
			while (plus.android.invoke(userCursor, 'moveToNext')) {
				let tampObj = {}
				var keyLen = plus.android.invoke(userCursor, 'getColumnCount');
				for (var i = 0; i < keyLen; i++) {
					var tampKey = plus.android.invoke(userCursor, 'getColumnName', i);
					var tampVal = plus.android.invoke(userCursor, 'getString', plus.android.invoke(
						userCursor,
						'getColumnIndex',
						tampKey));
					tampObj[tampKey] = tampVal;
				}
				tampArr.push(tampObj);
				console.log(tampObj)
			}

			if (tampArr) resolve(tampArr)
			if (Obj.success && typeof Obj.success == "function") {
				return Obj.success({
					code: 200,
					data: tampArr,
					msg: "获取成功"
				});
			}

		}, function() {
			if (Obj.error && typeof Obj.error == "function") {
				Obj.error({
					code: 404,
					msg: "获取失败"
				});
			}
		})
	})
}


/*
 * cs 2020-9-28
 * 新增日历
 */
function addEvent(Obj) {
	getCalendarJurisdiction(function() {
		// 查询是否有日历账号
		var calendarAccountList = plus.android.invoke(main.getContentResolver(), 'query', Uri.parse(
				calanderURL), null,
			null, null);

		var count = plus.android.invoke(calendarAccountList, "getCount");
		var tampArr = []
		while (plus.android.invoke(calendarAccountList, 'moveToNext')) {
			let tampObj = {}
			var keyLen = plus.android.invoke(calendarAccountList, 'getColumnCount');
			for (var i = 0; i < keyLen; i++) {
				var tampKey = plus.android.invoke(calendarAccountList, 'getColumnName', i);
				var tampVal = plus.android.invoke(calendarAccountList, 'getString', plus.android.invoke(
					calendarAccountList,
					'getColumnIndex',
					tampKey));
				tampObj[tampKey] = tampVal;
			}
			tampArr.push(tampObj);
		}
		console.log(tampArr);
		// 查询是否有固定账号
		let isHasAccout = false;
		let accout_id = null;

		tampArr.forEach(item => {
			if (item.name == 'tansuoshengya') {
				accout_id = item._id;
				isHasAccout = true;
			}
		})

		// 如果有账号直接写入日历
		if (isHasAccout) {
			Obj.eventObj.calendar_id = accout_id;
			var eventID = addEvent_tabel(Obj.eventObj)

		} else {
			// 添加账号
			accout_id = initCalendars();
			Obj.eventObj.calendar_id = accout_id;

			var eventID = addEvent_tabel(Obj.eventObj)
		}

		if (Obj.success && typeof Obj.success == "function") {
			Obj.success({
				code: 200,
				data: eventID,
				msg: "获取成功"
			});
		}

	}, function() {
		if (Obj.error && typeof Obj.error == "function") {
			Obj.error({
				code: 404,
				msg: "添加失败"
			});
		}
	})
}


/*
 * cs 2020-9-28
 * 删除日历
 * event_id 事件的ID
 * success 成功回调
 * error 失败回调
 */
function deleteEvent(Obj) {
	getCalendarJurisdiction(function() {
		console.log(Obj.event_id);
		var deleteUri = ContentUris.withAppendedId(Uri.parse(calanderEventURL), Obj.event_id);
		console.log(deleteUri);
		var rows = plus.android.invoke(main.getContentResolver(), "delete", deleteUri, null, null);

		if (Obj.success && typeof Obj.success == "function") {
			Obj.success({
				code: 200,
				data: rows,
				msg: "删除成功"
			});
		}

	}, function() {
		if (Obj.error && typeof Obj.error == "function") {
			Obj.error({
				code: 404,
				msg: "删除失败"
			});
		}
	})
}

/*
 * cs 2020-9-28
 * 修改日历事件
 * eventObj 参数必须要event_id
 */
function updataEvent(Obj) {
	getCalendarJurisdiction(function() {
		if (!Obj.eventObj.event_id) {
			if (Obj.error && typeof Obj.error == "function") {
				Obj.error({
					code: 404,
					msg: "添加失败"
				});
			}
		}

		var values = new ContentValues();
		if (Obj.eventObj.title) {
			values.put("title", Obj.eventObj.title)
		}
		if (Obj.eventObj.description) {
			values.put("description", Obj.eventObj.description)
		}
		if (Obj.eventObj.dtstart) {
			values.put("dtstart", Obj.eventObj.dtstart)
		}
		if (Obj.eventObj.dtstart) {
			values.put("dtend", Obj.eventObj.dtstart)
		}
		if (Obj.eventObj.rrule) {
			values.put("rrule", Obj.eventObj.rrule)
		}
		console.log(Obj.eventObj.event_id)
		var updateUri = ContentUris.withAppendedId(Uri.parse(calanderEventURL), Obj.eventObj.event_id);
		console.log(updateUri);
		var rows = plus.android.invoke(main.getContentResolver(), "update", updateUri, values, null, null);
		if (Obj.success && typeof Obj.success == "function") {
			Obj.success({
				code: 200,
				data: rows,
				msg: "修改成功"
			});
		}

	}, function() {
		if (Obj.error && typeof Obj.error == "function") {
			Obj.error({
				code: 404,
				msg: "修改成功"
			});
		}
	})
}



//添加账户  
function initCalendars() {
	var TimeZone = plus.android.importClass("java.util.TimeZone");
	var timeZone = TimeZone.getDefault();
	var ContentValues = plus.android.importClass("android.content.ContentValues");
	var value = new ContentValues();
	var Calendars = plus.android.importClass("android.provider.CalendarContract.Calendars");
	value.put("name", "tansuoshengya");
	value.put("account_name", "18071466586@163.com");
	value.put("account_type", "com.android.exchange");
	value.put("calendar_displayName", "全科提分能力");
	value.put("visible", 1);
	value.put("calendar_color", "-9206951");
	value.put("calendar_access_level", "700");
	value.put("sync_events", 1);
	value.put("calendar_timezone", plus.android.invoke(timeZone, "getID"));
	value.put("ownerAccount", "18071466586@163.com");
	value.put("canOrganizerRespond", 0);
	var Uri = plus.android.importClass("android.net.Uri");
	var calendarUri = Uri.parse("content://com.android.calendar/calendars");
	var buildUpon = plus.android.invoke(calendarUri, "buildUpon");
	var CalendarContract = plus.android.importClass("android.provider.CalendarContract");
	plus.android.invoke(buildUpon, "appendQueryParameter", CalendarContract.CALLER_IS_SYNCADAPTER, "true");
	plus.android.invoke(buildUpon, "appendQueryParameter", "account_name", "18071466586@163.com");
	plus.android.invoke(buildUpon, "appendQueryParameter", "account_type", "com.android.exchange");
	calendarUri = plus.android.invoke(buildUpon, "build");
	var newAccoutList = plus.android.invoke(plus.android.runtimeMainActivity().getContentResolver(), "insert",
		calendarUri,
		value);

	var newAccout_id;
	newAccout_id = plus.android.invoke(plus.android.invoke(newAccoutList, "getPathSegments"), "get", 1);

	return newAccout_id;
}


/*
 * 添加日历到表格
 * cs 2020-9-28
 * rrule 规则 FREQ=WEEKLY;WKST=SU;BYDAY=MO,TU,WE,TH,FR 每周的1 2 3 4 5
 * rrule='FREQ=DAILY;INTERVAL=5;WKST=SU' 每5天提醒
 * 每8天提醒一次，截止到20180808
 * rrule='FREQ=DAILY;UNTIL=20180808T093000;INTERVAL=8;WKST=SU'
 * dtstart 开始时间
 * eventTimezone 时区
 * dtend 结束时间 重复事件可以不用填
 */
function addEvent_tabel(Obj) {
	var TimeZone = plus.android.importClass("java.util.TimeZone");
	var timeZone = TimeZone.getDefault();
	var ContentValues = plus.android.importClass("android.content.ContentValues");
	var values = new ContentValues();
	values.put("calendar_id", Obj.calendar_id);
	values.put("title", Obj.title);
	values.put("description", Obj.description);
	values.put("dtstart", Obj.dtstart);
	values.put("dtend", Obj.dtstart);
	values.put("eventTimezone", plus.android.invoke(timeZone, "getID"));
	values.put("rrule", Obj.rrule);
	values.put("hasAlarm", 1); //是否闹钟提醒 默认提醒 因为大部分手机未实现此功能 故未实现
	var newEvent = plus.android.invoke(main.getContentResolver(), 'insert', Uri.parse(calanderEventURL), values);
	console.log(newEvent);
	var id = plus.android.invoke(newEvent, 'getLastPathSegment');
	console.log(id);
	var remindersObj = new ContentValues();
	remindersObj.put('event_id', id);
	remindersObj.put('minutes', '5');
	remindersObj.put('method', '1');
	plus.android.invoke(main.getContentResolver(), 'insert', Uri.parse(calanderRemiderURL), remindersObj);
	console.log('设置提醒成功');
	return id;
}




export {
	queryEvent,
	addEvent,
	deleteEvent,
	updataEvent
};
